package orm

import (
	"context"
	"fmt"
	"gitee.com/whilew/cream/pkg/basic_component/log"
	"gitee.com/whilew/cream/pkg/util/xcontext"
	"gorm.io/gorm/logger"
	"time"
)

type ormLoger struct {
	is_need_trace bool
	*log.Loger
}

func (l *ormLoger) LogMode(logger.LogLevel) logger.Interface {
	return l
}
func (l *ormLoger) Info(ctx context.Context, msg string, arg ...interface{}) {
	l.Clone().Info(fmt.Sprintf(msg, arg...))
}
func (l *ormLoger) Warn(ctx context.Context, msg string, arg ...interface{}) {
	l.Clone().Warn(fmt.Sprintf(msg, arg...))
}
func (l *ormLoger) Error(ctx context.Context, msg string, arg ...interface{}) {
	l.Clone().Error(fmt.Sprintf(msg, arg...))
}
func (l *ormLoger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
	if l.is_need_trace {
		sql, rows := fc()
		loger := l.Clone().WithDuration(begin)
		arg := xcontext.GetValueCtxKV(ctx)
		for k, v := range arg {
			loger.WithKV(k, v)
		}
		loger.Info(fmt.Sprintf("[trace] %s %d", sql, rows))
	}
}
